package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Range;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.sky.context.ThreadLocalUtil;
import com.sky.result.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.entity.Employee;
import com.sky.exception.BusinessException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //登录
    public Employee login(EmployeeDTO employeeDTO) {

        //1. 参数校验（非空判断）
        String username = employeeDTO.getUsername();
        String password = employeeDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new BusinessException(400, "账号或密码不能为空");
        }
        //2. 业务校验（能不能用）
        // 根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);
        //2.1 用户名是否存在
        if (employee == null) {
            //账号不存在
            throw new BusinessException(400, "账号不存在");
        }
        //2.2 密码比对
        if (!SecureUtil.md5(password).equals(employee.getPassword())) {
            //密码错误
            throw new BusinessException(400, "密码错误");
        }
        //2.3 判断状态
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new BusinessException(500, "账号被禁用");
        }
        //3. 完成业务
        //4. 返回结果
        return employee;
    }

    //添加员工信息
    @Override
    public void add(EmployeeDTO employeeDTO) {
        //1 参数校验
        empParamsCheck(employeeDTO);
        //2 业务校验（username phone idnumber）
        empBusinessCheck(employeeDTO);
        //3. 完成业务
        //3.1 DTO转PO
        Employee employee = BeanUtil.copyProperties(employeeDTO, Employee.class);
        //3.2 补全数据
        employee.setPassword(SecureUtil.md5("123456")); //默认密码
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(ThreadLocalUtil.getCurrentId()); //TODO
        employee.setUpdateUser(ThreadLocalUtil.getCurrentId()); //TODO
        //3.3 保存数据
        employeeMapper.insert(employee);
    }

    //员工业务校验
    private void empBusinessCheck(EmployeeDTO employeeDTO) {
        Employee emp = employeeMapper.getByUsername(employeeDTO.getUsername());
        if (emp != null) {
            throw new BusinessException(400, "账号已经被注册");
        }
        emp = employeeMapper.getByPhone(employeeDTO.getPhone());
        if (emp != null) {
            throw new BusinessException(400, "手机号已经被注册");
        }
        emp = employeeMapper.getByNumber(employeeDTO.getIdNumber());
        if (emp != null) {
            throw new BusinessException(400, "神风证已经被注册");
        }
    }

    //员工参数校验
    private void empParamsCheck(EmployeeDTO employeeDTO) {
        String username = employeeDTO.getUsername();
        String name = employeeDTO.getName();
        String phone = employeeDTO.getPhone();
        String idNumber = employeeDTO.getIdNumber();
        if (StrUtil.isBlank(username)) {
            throw new BusinessException(400, "账号不能为空");
        }
        if (StrUtil.isBlank(name)) {
            throw new BusinessException(400, "姓名不能为空");
        }
        if (StrUtil.isBlank(phone)) {
            throw new BusinessException(400, "手机号不能为空");
        }
        if (StrUtil.isBlank(idNumber)) {
            throw new BusinessException(400, "身份证号不能为空");
        }
    }

    //分页查询

    @Override
    public PageResult findByPage(String name, Integer page, Integer pageSize) {
        //1. 开启分页
        PageHelper.startPage(page, pageSize);
        //2. 查询
        List<Employee> list = employeeMapper.findByPage(name);
        PageInfo<Employee> pageInfo = new PageInfo<>(list);
        //3. 封装分页结果
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }
    //id回显
    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }

    //更新
    @Override
    public void update(EmployeeDTO employeeDTO) {
        //校验参数非空
        empParamsCheck(employeeDTO);
        //业务校验
        updateBusinessCheck(employeeDTO);
        //完成业务
        Employee employee = BeanUtil.copyProperties(employeeDTO, Employee.class);

        employee.setUpdateUser(ThreadLocalUtil.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);
    }

    //参数校验
    private void updateBusinessCheck(EmployeeDTO employeeDTO) {
        String username = employeeDTO.getUsername();
        String phone = employeeDTO.getPhone();
        String IdNumber = employeeDTO.getIdNumber();

        Employee employee = employeeMapper.getByUsername(username);
        if (employee != null && !employee.getId().equals(employeeDTO.getId())) {
            throw new BusinessException(400, "账号已经存在");
        }
        employee = employeeMapper.getByPhone(phone);
        if (employee != null && !employee.getId().equals(employee.getId())) {
            throw new BusinessException(400, "手机号已经存在");
        }
        employee = employeeMapper.getByNumber(IdNumber);
        if (employee != null && !employee.getId().equals(employee.getId())) {
            throw new BusinessException(400, "身份证号以存在");
        }

    }

    //启用禁用账号
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(ThreadLocalUtil.getCurrentId())
                .build();
        employeeMapper.update(employee);
    }

    //修改密码
    @Override
    public void updatedPassword(Long id, EmployeeDTO employeeDTO) {
        Employee emp=employeeMapper.getById(id);
        if (!emp.getPassword().equals(SecureUtil.md5(employeeDTO.getOldPassword()))){
           throw new BusinessException(400,"密码错误");
        }
        emp=Employee.builder()
                .id(id)
                .password(SecureUtil.md5(employeeDTO.getNewPassword()))
                .updateTime(LocalDateTime.now())
                .updateUser(ThreadLocalUtil.getCurrentId())
                .build();
        employeeMapper.update(emp);
    }
}